/**
 * Created by dcampus2011 on 16/1/26.
 *  sendRequest http 请求封装服务
 *  sessionRecover session 重新连接服务
 */
{
	angular
		.module('httpModule')
		.factory('http.sendRequest', sendRequest)
		.factory('http.sessionRecoverer', SessionRecover);

	/**
	 * @desc Angular 依赖注入
	 * @type {string[]}
	 */
	sendRequest.$inject = ['$http', 'utils.constant.config'];
	SessionRecover.$inject = ['$q', '$injector'];

	/**sendRequest
	 * @desc 封装http请求的主要方法，提供整个应用调用
	 * @param $http
	 * @param config
	 * @returns {Function}
	 */
	function sendRequest($http, config) {
		return function (action, paramData, local) {
			let Domain = config.sitePath;
			if (local) {
				Domain = '';
			}
			let req = {
				method: 'POST',
				url: Domain + action,
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				}
			};
			if (typeof(paramData) === 'string') {
				req.data = paramData;//定义字符串参数
			} else if (typeof(paramData) === 'object') {
				//把对象转换成序列化
				let keysArr = Object.keys(paramData),
					keysArrLength = keysArr.length,
					serialize = '';
				for (let i = 0; i < keysArrLength; i++) {
					serialize += keysArr[i] + '=' + paramData[keysArr[i]] + '&';
				}
				serialize = serialize.substring(0, (serialize.length - 1));
				req.data = serialize;
			}
			return $http(req);
		};
	}

	/****SessionRecover方法定义
	 * @desc 用于对登录超时进行重新登陆，及重发请求
	 * @param $q
	 * @param $injector
	 * @returns {{responseError: sessionRecoverer.responseError}}
	 * @constructor
	 */
	function SessionRecover($q, $injector) {
		let sessionRecoverer = {
			response: function (response) {
				//判断如果当前请求超时
				if (response.data
					&& typeof(response.data)=="object"
					&& ('resultCode' in response.data)
					&& response.data.resultCode==0
					&& response.data.message==="超时或未登录！") {
					let $state = $injector.get('$state');
					$state.go('tab.login');
				}
				else if(response.data
					&& typeof(response.data)=="object"
					&& ('resultCode' in response.data||'result'in response.data)
					&& (response.data.resultCode==0||response.data.result==0)
					&& response.data.message!=="超时或未登录！"){
					alert(response.data.message);
				}
				return response;//否则非登录超时，正常返回
			}
		};
		return sessionRecoverer;//返回Recover对象
	}
}


